<template>
    <div class="queryproduct">
        <product-filter :status="status" @search="search">
        </product-filter>
        <!--搜索之后把搜到的数据传递-->
        <Empty v-if="queryPros.length==0">没有搜到任何数据</Empty>
        <div class="productlist" v-if="queryPros.length!==0">
            <header style="margin: 24px 0">
                已选中
                <span class="choosenum">{{num}}</span>项
                <!--num 统计true的值-->
                <el-dropdown type="primary" split-button @command="handleCommand" style="margin-left: 24px;">
                    <span class="el-dropdown-link">
                        批量操作
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>批量下架</el-dropdown-item>
                    </el-dropdown-menu>

                </el-dropdown>
                <export-file :api-info="downloadGoodsApi" style="margin-left: 20px;">导出全部商品</export-file>

            </header>

            <el-table ref="multipleTable" :data="queryPros" border tooltip-effect="dark"
                      @selection-change="handleSelectionChange"
                      style="width: 100%;">
                <el-table-column type="selection" width="58">
                </el-table-column>
                <el-table-column prop="imgJson" label="商品图片" width="100">
                    <template slot-scope="scope">
                        <img :src="processImg(scope.row.imgJson)" style="margin-top: 8px">
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="商品名称">
                </el-table-column>
                <el-table-column label="类目" prop="categoryAndType">
                </el-table-column>
                <el-table-column label="最低租金" sortable>
                    <template slot-scope="scope">{{scope.row.displayRent | parsePrice}}</template>
                </el-table-column>
                <el-table-column label="总库存" sortable prop="stock">
                </el-table-column>
                <el-table-column label="租赁中" sortable prop="rentingAmount">
                </el-table-column>
                <el-table-column label="
新旧程度" sortable prop="oldLevelStr">
                </el-table-column>
                <el-table-column label="商品状态" prop="statusStr">
                </el-table-column>
                <!--四个时间动态渲染-->
                <el-table-column label="上架时间" sortable>
                    <template slot-scope="scope">
                        {{scope.row.putawayTime | parseTime}}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="setStore(scope.row.id)">
                            设置库存
                        </el-button>

                        <el-button type="text" @click="toStorage(scope.row.id,scope.$index)">下架</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog custom-class="setInventoryDialog" :title="proTitle+'的库存详情'" :visible.sync="setInventory">
                <div class="rentTimesel">
                    <el-button @click="batchSetStore">批量设置库存</el-button>
                </div>
                <el-table
                        :data="tableData"
                        border
                        style="width:100%;" @selection-change="selectHandle">
                    <el-table-column type="selection" width="58">
                    </el-table-column>
                    <el-table-column v-for="(item,index) in speciTitles" :label="item.specificationName" :key="index"
                                     :prop="'param'+(index+1)"
                                     width="120">
                    </el-table-column>
                    <el-table-column label="租期(天)" prop="leaseDay">

                    </el-table-column>
                    <el-table-column label="租金(元/天)" prop="rent">

                    </el-table-column>
                    <el-table-column label="目前库存" prop="stock">

                    </el-table-column>
                    <el-table-column label="调整后库存" width="120">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.newRent">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="setInventory= false">取 消</el-button>
                    <el-button type="primary" @click="commitStore">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="批量设置" :visible.sync="batchSet">
                已选中{{num1}}项
                <!--根据表格中勾选的项数来显示-->
                <el-form :model="form" :rules="rules" ref="form">
                    <el-form-item label="设置库存" label-width="200px" prop="store">
                        <el-input v-model="form.store"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="batchSet = false">取 消</el-button>
                    <el-button type="primary" @click="setStoreAll">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import productFilter from './components/product_filter.vue';
    import Empty from '@/components/Empty'
    import {getFirCategory} from '@/api/category'
    import {goodsTakeOffByIds, toStorage, updateBatch, getProSpecis, exportProductsLists} from '@/api/goods'
    import {stripscript, isNumber, IntergerIncludeZero, isInterger} from '@/utils/validate';
    import {host, osshost} from '@/api/util/fetch';
    import {showMessage} from '@/utils/message';
    import ExportFile from '@/components/ExportFile';


    export default {
        name: 'productStatusPutAway',
        components: {
            'product-filter': productFilter,
            'Empty': Empty,
            'export-file': ExportFile,
        },
        props: {
            state: {
                type: String,
                default: ""
            },
            isEdit: {
                type: Boolean,
                default: false
            },
            queryPros: {
                type: Array,
                default: []
            }
        },
        mounted() {
        },
        data() {
            let validatorMoney = (rule, value, callback) => {
                if (!IntergerIncludeZero(value)) {
                    callback(new Error('请输入数值!'))
                } else {
                    callback()
                }

            };
            return {
                status: '上架',
                setInventory: false,
                toEditor: false,
                statusTitle: '',
                num: 0,
                goodsId: 0,
                num1: 0,
//        设置库存table中的数据
//        响应报文中得到 数据  title
                ids: [],
                form: {
                    store: 0
                },
                rules: {
                    store: [
                        {required: true, message: '不能为空'},
                        {validator: validatorMoney, trigger: 'blur'}
                    ]
                },
                batchSet: false,
                speciTitles: [],
                tableData: [],
                specisIds: [],
                proTitle: '',

              downloadGoodsApi:{ //导出订单api
                url:'goods/exportGoods',
                method:'get',
                data:{},
              },
            }
        },
        created() {
//      将父组件传过来的status继续传递给product-filter.vue组件
            this.toEditor = this.isEdit;
        },
        methods: {
            search() {
                this.loading = true;
                setTimeout(() => {
                    this.loading = false;
                }, 300);

            },
            processImg(url) {
                if (url && url !== '' || url && url !== '[]') {
                    url = JSON.parse(url)[0].url;
                    return osshost + url + '?x-oss-process=image/resize,m_fixed,h_60,w_60';
                } else {
                    return '';
                }
            },
            getCategory() {
                getFirCategory()
                    .then((resp) => {
                        for (let item of resp.data.list) {
                            let tmp = {
                                value: item.id,
                                label: item.name,
                                disabled: item.enabled
                            };
                            this.category.push(tmp);
                        }
//                        console.log(this.category)
                    })
                    .catch((err) => {
//                        console.log(err)
                    })
            },
            handleSelectionChange(val) {
//                console.log(val);
                this.num = val.length;
                let arr = [];
                for (let item of val) {
                    arr.push(item.id)
                }
                this.ids = arr;
//                console.log(this.ids)
            },
            renderTable() {
//        通过子组件传过来的数据 赋值

            },
            toEdit() {
                this.toEditor = true;
                this.$emit("toEdit", this.toEditor)
            },
            toStorage(id, index) {
//                下架
                this.$confirm('此操作将下架该商品, 是否继续?', '确认下架', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let data = null;
                    if (typeof id !== 'number') {
                        data = id
                    } else {
                        data = [id];
                    }
                    goodsTakeOffByIds(data)
                        .then((resp) => {
//                            console.log(resp);
                            showMessage({
                                type: 'success',
                                title: '下架成功'
                            });
                            this.$emit('up-date', data);
                            this.$emit('is-change');
                        })
                        .catch((err) => {
//                            console.log(err)
                        });


                }).catch(() => {

                });
            },
            handleCommand() {
                //            批量操作
//            下架
                if (this.ids.length == 0) {
                    this.$message({
                        type: 'warning',
                        message: '您还没有选择要下架的商品'
                    });
                    return
                }
                this.toStorage(this.ids)
            },
            setStore(id) {
//                设置库存
                this.setInventory = true;
                this.goodsId = id;

                for (let item of this.queryPros) {
                    if (id == item.id) {
                        this.proTitle = item.category + '/' + item.type + '/' + item.brand + '/' + item.model;
                    }
                }
                this.getSpecis();
            },
            selectAll(selection) {
//                console.log(selection);
                this.num = selection.length
            },
            getSpecis() {
//                获取规格
                getProSpecis(this.goodsId)
                    .then((resp) => {
                        this.speciTitles = [];
//                处理表头
                        if (resp.data.list.length != 0) {
                            let name = null;
                            if (resp.data.list[0].specificationFirstName !== '') {
                                name = {
                                    specificationName: resp.data.list[0].specificationFirstName
                                };
                                this.speciTitles.push(name);
                            }
                            if (resp.data.list[0].specificationSecondName !== '') {
                                let name = {
                                    specificationName: resp.data.list[0].specificationSecondName
                                };
                                this.speciTitles.push(name);
                            }
                            if (resp.data.list[0].specificationThirdName !== '') {
                                let name = {
                                    specificationName: resp.data.list[0].specificationThirdName
                                };
                                this.speciTitles.push(name);
                            }
                            if (resp.data.list[0].specificationFourthName !== '') {
                                let name = {
                                    specificationName: resp.data.list[0].specificationFourthName
                                };
                                this.speciTitles.push(name);
                            }
                            if (resp.data.list[0].specificationFifthName !== '') {
                                let name = {
                                    specificationName: resp.data.list[0].specificationFifthName
                                };

                                this.speciTitles.push(name);
                            }
//                            console.log(this.speciTitles)
                            this.tableData = [];
                            for (let item of resp.data.list) {
                                let data = {
                                    "param1": item.specificationFirst ? item.specificationFirst : '',
                                    "param2": item.specificationSecond ? item.specificationSecond : '',
                                    "param3": item.specificationThird ? item.specificationThird : '',
                                    "param4": item.specificationFourth ? item.specificationFourth : '',
                                    "param5": item.specificationFifth ? item.specificationFifth : '',
                                    leaseDay: item.leaseDay,
                                    rent: item.rent / 100,
                                    stock: item.stock,
                                    newRent: '',
                                    id: item.id
                                };
                                this.tableData.push(data);

                            }
                        }

                    }).catch((err) => {
//                    console.log(err)
                })
            },
            setStoreAll() {
//                批量设置一样的
                let data = [];
                for (let item of this.specisIds) {
                    let a = {
                        id: item.id,
                        stock: this.form.store - 0
                    };
                    data.push(a);
                }
                for (let item of data) {
                    if (!isInterger(item.stock)) {
//                        如果不是正整数
                        this.$message.error('库存设置有误!');
                        return;
                    }
                }
//                console.log(data);
                updateBatch(data)
                    .then((resp) => {
//                        console.log(resp);
                        showMessage({
                            type: 'success',
                            title: '批量设置库存成功'
                        });

                        this.batchSet = false;
                        this.setInventory = false;
                        this.$emit('is-change');
                    })
                    .catch((err) => {
//                        console.log(err)
                    });

            },
            selectHandle(val) {
//                设置库存的选择事件
//                console.log(val);
                this.num1 = val.length;
                this.specisIds = [];
                for (let item of val) {
                    let data = {
                        id: item.id,
                    };
                    this.specisIds.push(data);
                }
            },
            commitStore() {
                let data = [];
//                console.log(this.tableData)
                for (let item of this.tableData) {
//                    console.log(item);
                    let a = {
                        id: item.id,
                        stock: item.newRent ? (item.newRent - 0) : (item.stock - 0)
                    };
                    data.push(a);
                }
                //假设全部为0
                let arr = data.filter(item => {
                    return item.stock === 0
                });
//                console.log(arr);
                if (arr.length == data.length) {
                    this.$message.error('商品上架中，库存不能全部设置为0!');
                    return;
                }
//                console.log(data);
                updateBatch(data)
                    .then((resp) => {
//                        console.log(resp);
                        showMessage({
                            type: 'success',
                            title: '设置库存成功'
                        });
                        this.$emit('is-change');
                        this.setInventory = false;
                    })
                    .catch((err) => {
//                        console.log(err)
                    });
            },
            batchSetStore() {
                if (this.specisIds.length == 0) {
                    this.$message({
                        type: 'warning', message: '您还没有选择商品！'
                    });
                    return;
                }
                this.batchSet = true;
            },
        }
    }
</script>

<style lang="less">
    .setInventoryDialog {
        width: 68%;
    }
</style>